package cc.linker.steplink.crm.merchanth5.service;

import cc.linker.steplink.crm.merchanth5.dao.EnrollActiveDao;
import cc.linker.steplink.crm.merchanth5.dao.OverViewInfoDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class OverViewInfoService {
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Autowired
    private OverViewInfoDao overViewInfoDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private EnrollActiveDao enrollActiveDao;

    private static final DateTimeFormatter ADF = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    public void goodsData(String goodsId, String enrollId, Integer type, String time, Integer second,
                          String storeName, Integer buyCount, Integer amount, String customerId, String orgId,String linkId) {
        Map<String, Object> param = new HashMap<>();
        if(StringUtils.isEmpty(goodsId)){
            param.put("goodsId", null);
        }else{
            param.put("goodsId", goodsId);
        }
        param.put("enrollId", enrollId);
        param.put("type", type);
        param.put("customerId", customerId);
        param.put("orgId", orgId);
        param.put("second", second);
        param.put("buyCount", buyCount);
        String datetime = df.format(LocalDateTime.now());
        param.put("datetime", datetime);
        LOGGER.info("商品数据goodsData-->params:"+ JSON.toJSONString(param));
        String typeName = this.getTypeNameByTypeCode(goodsId, enrollId, type, time, storeName, buyCount, amount, customerId,linkId);
        if (StringUtils.isEmpty(typeName)) {
            return;
        }
        param.put("record", typeName);
        overViewInfoDao.addGoodsData(param);
//        mongoTemplate.insert(param, MongoConstant.GOODS_DATA);
    }

    /**
     * 点击了xxx
     * 分享了xxx
     * 购买了xxx
     * 购物车加入了xxx
     * 浏览了xxx120时-30分-12秒
     * 进入了店铺xxx
     * 1-点击\2-分享\3-购买\4-加入购物车\5-商品浏览时长\6-进入店铺
     */
    private String getTypeNameByTypeCode(String goodsId, String enrollId, Integer type, String time, String storeName,
                                         Integer buyCount, Integer amount, String customerId,String linkId) {
        String result;
        String goodsName = "";
        if (!StringUtils.isEmpty(goodsId)) {
            goodsName = purchaseProcessDao.getGoodsNameByGoodsId(goodsId);
        } else if (!StringUtils.isEmpty(enrollId)) {
            goodsName = purchaseProcessDao.getEnrollNameByEnrollId(enrollId);
        }
        if (StringUtils.isEmpty(goodsName) && type != 6) {
            return null;
        }
        String row = null;
        switch (type) {
            case 1:
                result = "点击了" + goodsName;
                row = "VIEW_NUM";
                break;
            case 2:
                result = "分享了" + goodsName;
                row = "SHARE_NUM";
                break;
            case 3:
                result = "购买了" + goodsName;
                row = "DEAL_NUM";
                break;
            case 4:
                result = "购物车加入了" + goodsName;
                row = "ADD_NUM";
                break;
            case 5:
                result = "浏览了" + goodsName + time;
                break;
            case 6:
                result = "进入了店铺" + storeName;
                break;
            default:
                result = "";
                break;
        }
        // 商品行为
        if (row != null && !StringUtils.isEmpty(goodsId)) {
            if (type == 3) {
                if (buyCount != null && buyCount > 0) {
                    // 更新支付商品件数
                    this.insertOrUpdate("PAY_GOODS_NUM", goodsId, buyCount, true);
                }
                if (amount != null && amount > 0) {
                    this.insertOrUpdate("PAY_AMOUNT", goodsId, amount, true);
                }
                // 购买
                Integer integer = purchaseProcessDao.countGoodsByCustomerIdAndGoodsId(customerId, goodsId);
                if (integer == 0) {
                    // 更新支付人数
                    this.insertOrUpdate("PAY_NUM", goodsId, buyCount, false);
                }
                this.insertOrUpdate(row, goodsId, buyCount, false);
            }
            if (type == 4 && buyCount != null && buyCount > 0) {
                // 加购件数
                this.insertOrUpdate("ADD_GOODS_NUM", goodsId, buyCount, true);
                // 加购次数 每次默认1
                this.insertOrUpdate("ADD_TIMES", goodsId, 1, true);
                // 加购人数去重
                Map<String,Object> query = new HashMap<>();
                query.put("customerId",customerId);
                query.put("goodsId",goodsId);
                query.put("type",4);
                Integer count = overViewInfoDao.countGoodsData(query);
//                Query query = new Query();
//                query.addCriteria(Criteria.where("customerId").is(customerId).and("goodsId").is(goodsId).and("type").is(4));
//                long count = mongoTemplate.count(query, MongoConstant.GOODS_DATA);
                if (count == 0) {
                    // 更新 加购人数
                    this.insertOrUpdate("ADD_NUM", goodsId, buyCount, false);
                }
            }
            if (type == 1) {
                // 浏览次数
                Map<String,Object> query = new HashMap<>();
                query.put("customerId",customerId);
                query.put("goodsId",goodsId);
                query.put("type",1);
                Integer count = overViewInfoDao.countGoodsData(query);
//                Query query = new Query();
//                query.addCriteria(Criteria.where("customerId").is(customerId).and("goodsId").is(goodsId).and("type").is(1));
//                long count = mongoTemplate.count(query, MongoConstant.GOODS_DATA);
                if (count == 0) {
                    // 更新访客数
                    this.insertOrUpdate("GUEST_NUM", goodsId, buyCount, false);
                }
                this.insertOrUpdate(row, goodsId, buyCount, false);
            }
            if( type == 2 ){
                // 分享次数
                this.insertOrUpdate(row, goodsId, buyCount, false);
            }
        }
        // 报名行为
        if (row != null && !StringUtils.isEmpty(enrollId)){
            if (type == 1) {
                Map<String,Object> query = new HashMap<>();
                query.put("customerId",customerId);
                query.put("enrollId",enrollId);
                query.put("type",1);
                Integer count = overViewInfoDao.countGoodsData(query);

                if (count == 0) {
                    Map<String, Object> enrollInfo = enrollActiveDao.getInfo(query);
                    if ("1".equals(enrollInfo.get("isRepeat").toString())) {
                        stringRedisTemplate.opsForValue().set("enroll:enroll_overview_guestnum"+enrollId+customerId, "1");
                    }
                    // 更新访客数
                    this.insertOrUpdateEnroll("GUEST_NUM", enrollId, buyCount, false);
                }
                // 记录 报名的数据
                this.insertOrUpdateEnroll(row, enrollId, buyCount, false);
            }
            if(type == 2){
                // 分享行为
                this.insertOrUpdateEnroll(row, enrollId, buyCount, false);
            }
            if(type == 3){
                // 购买行为
                if (buyCount != null && buyCount > 0) {
                    // 更新报名人数
                    this.insertOrUpdateEnroll("PAY_NUM", enrollId, buyCount, true);
                }
                if (amount != null && amount > 0) {
                    this.insertOrUpdateEnroll("PAY_AMOUNT", enrollId, amount, true);
                }
                // 成交单数
                this.insertOrUpdateEnroll(row, enrollId, buyCount, false);
            }
        }
        try {
            if(!StringUtils.isEmpty(linkId)){
                this.pushOperateData(goodsId,linkId,goodsName,time,storeName,type);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("内容库推送失败！");
        }
        return result;
    }

    public void insertOrUpdateEnroll(String row, String enrollId, Integer buyCount, boolean count) {
        String date = ADF.format(LocalDateTime.now());
        Map<String, Object> map = new HashMap<>();
        map.put("row", row);
        map.put("date", date);
        map.put("enrollId", enrollId);
        if (count) {
            map.put("count", buyCount);
            overViewInfoDao.insertOrUpdateEnrollDataBuyCount(map);
            overViewInfoDao.insertOrUpdateEnrollDataSummaryByCount(map);
        } else {
            overViewInfoDao.insertOrUpdateEnrollData(map);
            overViewInfoDao.insertOrUpdateEnrollDataSummary(map);
        }
    }

    private void insertOrUpdate(String row, String goodsId, Integer buyCount, boolean count) {
        String date = ADF.format(LocalDateTime.now());
        Map<String, Object> map = new HashMap<>();
        map.put("row", row);
        map.put("date", date);
        map.put("goodsId", goodsId);
        if (count) {
            map.put("count", buyCount);
            overViewInfoDao.insertOrUpdateGoodsDataBuyCount(map);
            overViewInfoDao.insertOrUpdateGoodsDataSummaryByCount(map);
        } else {
            overViewInfoDao.insertOrUpdateGoodsData(map);
            overViewInfoDao.insertOrUpdateGoodsDataSummary(map);
        }
    }

    public String getOrgIdByCustomerId(String customerId) {
        return overViewInfoDao.getOrgIdByCustomerId(customerId);
    }

    private void pushOperateData(String goodsId,String linkId,String goodsName,String lookGoodsTime,String shopName,Integer type){
        Map operateMap = new HashMap();
        switch (type) {
            case 1:
               operateMap.put("linkId",linkId);
               operateMap.put("operate",14);
               operateMap.put("goodsName",goodsName);
               operateMap.put("goodsId",goodsId);
                break;
            case 2:
                operateMap.put("linkId",linkId);
                operateMap.put("operate",18);
                operateMap.put("goodsName",goodsName);
                operateMap.put("goodsId",goodsId);
                break;
            case 3:
                break;
            case 4:
                operateMap.put("linkId",linkId);
                operateMap.put("operate",15);
                operateMap.put("goodsName",goodsName);
                operateMap.put("goodsId",goodsId);
                break;
            case 5:
                operateMap.put("linkId",linkId);
                operateMap.put("operate",16);
                operateMap.put("goodsName",goodsName);
                operateMap.put("lookGoodsTime",lookGoodsTime);
                operateMap.put("goodsId",goodsId);
                break;
            case 6:
                operateMap.put("linkId",linkId);
                operateMap.put("operate",17);
                operateMap.put("shopName",shopName);
                operateMap.put("goodsId",goodsId);
                break;
            default:
                break;
        }
        if (operateMap.size()>0){
            LOGGER.info("给内容库发消息" + com.alibaba.fastjson.JSON.toJSONString(operateMap));
        }
    }
}
